package com.cms.ffmpeg

import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.android.baselibrary.arouter.ArouterContains
import com.android.baselibrary.base.BaseActivity
import com.bumptech.glide.Glide
import com.cms.ffmpeg.databinding.ActivityFfmpegMainBinding
import java.io.File

@Route(path = ArouterContains.FFMPEG)
open class FfmpegMainActivity : BaseActivity<ActivityFfmpegMainBinding>() {
    private var path = ""
    private var progressDialog: ProgressDialog? = null

    // 视频路径
    private var videoPath: String? = null


    override fun getLayoutId(): Int = R.layout.activity_ffmpeg_main

    override fun initView() {
        path = externalCacheDir?.path + "/Camera/gif/"
        if (!File(path).exists()) {
            File(path).mkdirs()
        }
    }

    override fun initListener() {
        mBinding.btnPicture.setOnClickListener(View.OnClickListener {
            val intent = Intent(Intent.ACTION_PICK)
            intent.setDataAndType(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                "video/*"
            )
            val chooserIntent = Intent.createChooser(intent, null)
            startActivityForResult(chooserIntent, 1)
        })
        mBinding.btnConvert.setOnClickListener {
            Glide.with(this@FfmpegMainActivity).clear(mBinding.ivGif)
            if (videoPath == null) {
                Toast.makeText(this@FfmpegMainActivity, "请选择视频", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            // 截取视频的前100帧

            // 截取视频的前100帧
           // val cmd = "ffmpeg -i $videoPath -vframes 1 -y -f gif -s 480×320 ${path}video_100.gif"

            val cmd = CmdList()
            cmd.append("ffmpeg")
                .append("-i")
                .append(videoPath)
                .append("-vframes")
                .append("10")
                .append("-y")
                .append("-f")
                .append("gif")
                .append("-s")
                .append("480×320")
                .append("${path}video_100.gif")
            val width = 480
            val height = 320

           /* cmd.append("ffmpeg")
                .append("-ss")
                .append("00:00:00")
                .append("-to")
                .append("00:00:03")
                .append("-i")
                .append(videoPath)
                .append("-vf")
                .append("scale=$width:$height:force_original_aspect_ratio=decrease,pad=$width:$height:(ow-iw)/2:(oh-ih)/2")
                .append("-b:v")
                .append("1M")
                .append("-preset")
                .append("ultrafast")
                .append("-threads")
                .append("5")
                .append("-y")
                .append("${path}video_1.mp4")*/
            //ffmpeg -ss [start] -t [duration] -accurate_seek -i [in].mp4 -codec copy [out].mp4
            /*cmd.append("ffmpeg").append("-ss").append("00:00:00").append("-t").append("00:01:01").append("-accurate_seek")
                .append("-preset")
                .append("ultrafast")
                .append("-threads")
                .append("5")
                .append("-i").append(videoPath).append("${path}video_1.mp4")*/

            // 显示loading
            // 显示loading
            progressDialog = ProgressDialog(this)
            progressDialog?.setTitle("截取中...")
            progressDialog?.show()

            /*     object : Thread() {
                     override fun run() {
                         super.run()
                         // 执行指令
                         Log.i("执行命令", "开始执行$cmd")
                         val a: Int = cmdRun(cmd)
                         Log.i("执行命令", a.toString() + "")

                         // 隐藏loading
                         runOnUiThread {

                         }
                     }
                */// }.start()
          VideoUtils.getInstance().execCmd(cmd, object : VideoUtils.OnRunListener {
                override fun onSuccess(outPath: String?) {
                   runOnUiThread {
                       progressDialog?.dismiss()
                       progressDialog = null
                       // 显示gif
                       Glide.with(this@FfmpegMainActivity)
                           .load(File("$path/video_100.gif"))
                           .into(mBinding.ivGif)
                   }
                }

                override fun onFailure() {
                    Log.i("VideoUtils", "onFailure: 失敗")
                }

                override fun onProgress(progress: Long) {
                    Log.i("VideoUtils", "onProgress: progress:"+progress)
                }
            })
           // val cmds = cmd.toTypedArray<String>()
          //  RxFFmpegInvoke.getInstance().runCommand(cmd)

        }
    }
    /*    private fun cmdRun(cmd: String): Int {
            val regulation = "[ \\t]+"
            val split = cmd.split(regulation.toRegex()).dropLastWhile { it.isEmpty() }
                .toTypedArray()
            return run(split)
        }*/


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1 && resultCode == RESULT_OK) {
            val uri = data?.data
            videoPath = audioUriToRealPath(this, uri)
            Log.i("视频路径", videoPath + "")
        }
    }

    fun audioUriToRealPath(context: Context?, uri: Uri?): String? {
        if (context == null || uri == null) {
            return null
        }
        var cursor: Cursor? = null
        val projection = arrayOf(MediaStore.Audio.Media.DATA)
        try {
            cursor = context.contentResolver.query(uri, projection, null, null, null)
            if (cursor != null) {
                val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)
                cursor.moveToFirst()
                return cursor.getString(columnIndex)
            }
        } finally {
            cursor?.close()
        }
        return null
    }


}